package com.cupk.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.extra.servlet.ServletUtil;
import com.cupk.common.Result;
import com.cupk.dto.AdminDTO;
import com.cupk.entity.Admin;
import com.cupk.entity.TeleRequest;
import com.cupk.entity.VerificationCodeRequest;
import com.cupk.mapper.AdminMapper;
import com.cupk.service.AdminService;
import com.cupk.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 名称AdminController
 * 描述管理员类
 *
 * @version 1.0
 * @author:XiongRuiKai
 * @datatime:2023-06-11 09:50
 */
@Slf4j
@RestController
@RequestMapping("/admins")
public class AdminController {

    @Autowired
    AdminService adminService;

    @Autowired
    RedisService redisService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public static final String YPCURL = "http://10.151.89.67/";

    /**
     *
     * @author yjh
     * @date 2023/6/11 15:55
     3.1.1 管理员身份证号码与密码登录
     */
    @GetMapping("/idcard")
    @CrossOrigin(origins = {YPCURL, "http://localhost:8080/"}) // 修改为Vue应用的地址
    public Result loginByPassword(String idCard, String password, HttpServletResponse response) {
        System.out.println(idCard+ "| " + password);
       return adminService.loginByPassword(idCard, password, response);
    }


    /**
     *
     * @author yjh
     * @date 2023/6/11 15:55
    3.1.2 管理员手机号校验，并发送验证码
     */
    @PostMapping("/sendTeleCodeToAdmin")
//    @CrossOrigin(origins = {"http://10.151.80.33:80/", "http://localhost:8080/"}) // 修改为Vue应用的地址
    public Result sendTeleCodeToAdmin(@RequestBody TeleRequest request, HttpServletResponse response) throws Exception {
        String tele = request.getTele();
        if (tele == null) {
            return new Result(0, "电话号为空", false);
        }
        System.out.println("==>" + tele);
        return adminService.sendTeleCodeToAdmin(tele, response);
    }

    /**
     *
     * @author yjh
     * @date 2023/6/11 15:55
    3.1.5 校验管理员验证码，进而放行或拦截
     */
    @PostMapping("/verificationCode")
    @CrossOrigin(origins = {YPCURL, "http://localhost:8080/"}) // 修改为Vue应用的地址
    public Result verificationCode(@RequestBody VerificationCodeRequest verificationCodeRequest, HttpServletRequest request, HttpServletResponse response){
            String verificationCode = verificationCodeRequest.getVerificationCode();
            System.out.println("解析出来的验证码如下：" + verificationCode);
            return redisService.verificationCode(request, response,verificationCode);
    }

    /**
     *
     * @author yjh
     * @date 2023/6/11 15:55
    3.2.1 返回姓名到前端
     */
    @PostMapping("/getAdminName")//http://localhost:8088/admins/getAdminName
    @CrossOrigin(origins = {YPCURL, "http://localhost:8080/"}) // 修改为Vue应用的地址
    public Result getAdminName(HttpServletRequest request){
        return new Result(1, null, adminService.getAdminName(request));
    }

    /**
     *
     * @author yjh
     * @date 2023/6/11 15:55
        生成邀请码，并存入redis
     */
    @PostMapping("/createMagicCode")//http://localhost:8088/admins/createMagicCode
    @CrossOrigin(origins = {YPCURL, "http://localhost:8080/"}) // 修改为Vue应用的地址
    public Result createMagicCode(HttpServletRequest request, Integer level){
        System.out.println("level:" + level);

        if(oneLevelJudeg(request) == true){
            String magicCode = adminService.createMagicCode(request, level);
            return new Result(0, null, magicCode);
        }
        else {
            return new Result(0, "你没有一级管理员权限",false);
        }
    }

    /**
     *
     * @author yjh
     * @date 2023/6/11 15:55
    判断是否有一级权限
     */
    @PostMapping("/oneLevelJudeg")//http://localhost:8088/admins/oneLevelJudeg
    @CrossOrigin(origins = {YPCURL, "http://localhost:8080/"}) // 修改为Vue应用的地址
    public boolean oneLevelJudeg(HttpServletRequest request)throws ClassCastException{
        String token = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    token = cookie.getValue();
                    System.out.println("token = " + token);
                }
            }
        }
        if(token == null){
            return false;
        }
        //2、基于token，获取redis中的用户
        final Map<Object, Object> adminMap = stringRedisTemplate.opsForHash().entries("login:token:" + token);
        System.out.println(adminMap);
        Object value = adminMap.get("level");
        System.out.println(value);
        if (value instanceof String && "1".equals(value))
        {
            return true;
        }
        else {
            return false;
        }
    }

    /**
     *
     * @author yjh
     * @date 2023/6/11 15:55
    判断是否有二级及以上权限
     */
    @PostMapping("/twoLevelJudeg")//http://localhost:8088/admins/twoLevelJudeg
    @CrossOrigin(origins = {YPCURL, "http://localhost:8080/"}) // 修改为Vue应用的地址
    public boolean twoLevelJudeg(HttpServletRequest request)throws ClassCastException{
        String token = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("token")) {
                    token = cookie.getValue();
                }
            }
        }
        if(token == null){
            return false;
        }
        //2、基于token，获取redis中的用户
        final Map<Object, Object> adminMap = stringRedisTemplate.opsForHash().entries("login:token:" + token);
        Object value = adminMap.get("level");
        System.out.println(value);
        if (value instanceof String && "1".equals(value))
        {
            return true;
        }
        else if (value instanceof String && "2".equals(value))
        {
            return true;
        }
        else {
            return false;
        }
    }


    /**
     *
     * @author yjh
     * @date 2023/6/11 15:55
    3.3.2 数据库中加入新管理员信息
     */
    @PostMapping("/addAdmin")//http://localhost:8088/admins/addAdmin
    @CrossOrigin(origins = {YPCURL, "http://localhost:8080/"}) // 修改为Vue应用的地址
    public Result addAdmin(@RequestBody Admin admin,  HttpServletResponse response) throws Exception {
        admin.setState(1);
        System.out.println(admin);
        boolean flag = adminService.addAdmin(admin,response);
        return flag ? new Result(1, null,flag) : new Result(0, null,flag);
    }

    /**
     *
     * @author yjh
     * @date 2023/6/11 15:55
    为注册的账户进行验证码校验
     */
    @PostMapping("/verificationCodeOnRegister")
    @CrossOrigin(origins = {YPCURL, "http://localhost:8080/"}) // 修改为Vue应用的地址
    public Result verificationCodeOnrRegister(@RequestBody VerificationCodeRequest verificationCodeRequest, HttpServletRequest request, HttpServletResponse response){
        String verificationCode = verificationCodeRequest.getVerificationCode();
        System.out.println("解析出来的验证码如下：" + verificationCode);
        return redisService.verificationCodeOnRegister(request, response,verificationCode);
    }

    /**
     *
     * @author yjh
     * @date 2023/6/11 15:55
    根据邀请码判断管理员是否能验证通过，并给出级别
     */
    @GetMapping("/analyseInviteCode/{inviteCode}")//http://localhost:8088/admins/analyseInviteCode
    @CrossOrigin(origins = {YPCURL, "http://localhost:8080/"}) // 修改为Vue应用的地址
    public Result analyseInviteCode(@PathVariable String inviteCode, HttpServletRequest request){
        System.out.println("inviteCode" + inviteCode);
        return  adminService.analyseInviteCode(inviteCode, request);
    }
}


